package com.app.lxx.pregnancyberth.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.app.lxx.pregnancyberth.Mvp.Presenter.CurrencyPresenter;
import com.app.lxx.pregnancyberth.Mvp.View.CurrencyView;
import com.app.lxx.pregnancyberth.R;
import com.app.lxx.pregnancyberth.base.BaseFragment;
import com.app.lxx.pregnancyberth.easyphone.EasyLinphone;
import com.app.lxx.pregnancyberth.easyphone.callback.PhoneCallback;
import com.app.lxx.pregnancyberth.easyphone.callback.RegistrationCallback;
import com.app.lxx.pregnancyberth.easyphone.service.LinphoneService;
import com.app.lxx.pregnancyberth.ui.ControllerActivity;
import com.app.lxx.pregnancyberth.ui.entity.ScreenSetData;
import com.app.lxx.pregnancyberth.ui.entity.UserInfoEntity;
import com.app.lxx.pregnancyberth.ui.entity.WardRoundEntity;
import com.app.lxx.pregnancyberth.widge.ChineseToSpeech;
import com.app.lxx.pregnancyberth.widge.LoadDailog.LoadDialog;
import com.app.lxx.pregnancyberth.widge.Recycler.MyRecycleAdapter;
import com.app.lxx.pregnancyberth.widge.SharedPreferencesUtils;
import com.app.lxx.pregnancyberth.widge.UserInfo;
import com.app.lxx.pregnancyberth.widge.UtilsManage;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.google.gson.Gson;

import org.linphone.core.LinphoneCall;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by Lxx on PregnancyManage
 * 2019/8/5 15:28 星期一
 * Details：查房记录
 */
public class WardRoundFragement extends BaseFragment<CurrencyPresenter> implements CurrencyView,View.OnClickListener {

    private TextView  tt_notes;
    private TextView wardroundName;
    private TextView wardroundAge;
    private TextView wardroundTime;
    private TextView wardroundStarts;
    private RecyclerView myRecyclerView;
    private TextView lastPage;
    private TextView nextPage;
    private ArrayList<WardRoundEntity.DataBean> arrayList = new ArrayList<>();
    private MyRecycleAdapter<WardRoundEntity.DataBean> myRecycleAdapter;


    protected SharedPreferencesUtils shareference;
    private TextView targetidText;
    private View mToggleSpeaker, mToggleMute;
    private ImageView mHangUp, mCallIn;
    private boolean isUpDateStatus = true;//是否需要更新通话状态
    private boolean inComingCall = false;
    private boolean isBusy = false;  //是否正在通话中。true 表示正忙 false 表示为不忙。
    //private boolean isAnswer = false;  //是否正在通话中。true 表示正忙 false 表示为不忙。
    private boolean isCallPhone = false;
    String lastText = "";
    long lastTime = 0;
    CountDownTimer mSpeechTextTimer;
    private ChineseToSpeech chineseToSpeech;

    private View four_myalbum, four_ebook, four_phoneCall, four_mind, root_view, calling_view;
    private LinearLayout controlView;
    private View view_front_black;
    private View view_clack_black;

    private ScreenSetData mScreenSetData;//??
    private UserInfoEntity.DataBean maternalData;



    private void startLoadCallLogTimer() {
        CountDownTimer loadCallLogTimer = null;

        if (loadCallLogTimer != null) {
            loadCallLogTimer.cancel();
        }
        new CountDownTimer(1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                Log.d("ddd", "onTick");
            }

            @Override
            public void onFinish() {
                loadCallLogs();
            }
        }.start();
    }

    private void loadCallLogs() {
        HashMap<String, String> map = new HashMap<>();
        map.put("no", this.shareference.getLinPhonDataZh());
        map.put("call_status", "");
//        getP().requestPost(type_load_calllogs, UrlManage.APP_URL + "doctor/newcalllist", map);
    }



    String phoneNumber = "";
    private boolean isHavePeople = true;
    private void requestImfoIndex() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("house_id", shareference.getUserHouseID()); //	房间id  21
        hashMap.put("bed_id", shareference.getUserBedID());//   	床位id  11

    }


    private void initView() {
        shareference = new SharedPreferencesUtils(getActivity());
        targetidText = getView().findViewById(R.id.targetid_text);
        mHangUp = getView().findViewById(R.id.hang_up);
        mCallIn = getView().findViewById(R.id.accept_call);
        mToggleSpeaker = getView().findViewById(R.id.toggle_speaker);
        mToggleMute = getView().findViewById(R.id.toggle_mute);
        calling_view = getView().findViewById(R.id.calling_view);

        four_myalbum = getView().findViewById(R.id.four_myalbum);
        four_ebook = getView().findViewById(R.id.four_ebook);
        four_phoneCall = getView().findViewById(R.id.four_phoneCall);
        four_mind = getView().findViewById(R.id.four_mind);
        controlView = getView().findViewById(R.id.intelligentControl_view);
        root_view = getView().findViewById(R.id.root_view);
        view_front_black = getView().findViewById(R.id.view_front_black);
        view_clack_black = getView().findViewById(R.id.view_clack_black);

        //设置挂断按钮
        mHangUp.setOnClickListener(this);
        mCallIn.setOnClickListener(this);
    }
    private void speechText(String text) {
        Log.e("speechText", "speechText:" + text);
        long time = System.currentTimeMillis();
        if (isBusy || (lastText.equals(text) && time - lastTime < 1000 * 5)) {//通话中 或者间隔不到5秒 或者重复播音  都忽略
            Log.e("speechText", "---ignore speechText:" + text);
            return;
        }
        lastTime = time;
        lastText = text;
        chineseToSpeech.speech(text);
        if (inComingCall) {
            lastText = "";
            lastTime = 0;
            isBusy = false;
            if (mSpeechTextTimer != null) {
                mSpeechTextTimer.cancel();
            }
            mSpeechTextTimer = new CountDownTimer(10 * 1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {

                }

                @Override
                public void onFinish() {
                    if (inComingCall) {
                        speechText("护士端呼叫...");
                    }
                }
            }.start();
        }
    }
    private void setDelayTimeToScreen() {
        try {
            long blackScreenTime = 30;//暂定单位为分钟
            if (mScreenSetData != null) {
                blackScreenTime = Long.parseLong(mScreenSetData.getData().getJg_time());
            }
            blackScreenTime = 1;//todo test
            blackScreenTime = System.currentTimeMillis() + blackScreenTime * 60 * 1000;
            view_front_black.setTag(blackScreenTime);
            LogUtils.e("current:" + TimeUtils.millis2String(System.currentTimeMillis()),
                    "close:" + TimeUtils.millis2String(blackScreenTime));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void initLinPhoneCall() {
        chineseToSpeech = new ChineseToSpeech(getActivity());

        String linPhonDataIp = shareference.getLinPhonDataIp();
        String linPhonDataDq = shareference.getLinPhonDataDq();
        String linPhonDataZh = shareference.getLinPhonDataZh();
        String linPhonDataMm = shareference.getLinPhonDataMm();
        PhoneCallback phoneCallback = new PhoneCallback() {
            @Override
            public void incomingCall(LinphoneCall linphoneCall) {
                // 来电状态
                super.incomingCall(linphoneCall);
                calling_view.setVisibility(View.VISIBLE);
                EasyLinphone.toggleSpeaker(true);
                targetidText.setText("来电中...");
                inComingCall = true;
                speechText("护士端呼叫...");
                mCallIn.setVisibility(View.VISIBLE);
                mHangUp.setVisibility(View.VISIBLE);

                if (controlView.getVisibility() == View.VISIBLE) {
                    controlView.setVisibility(View.GONE);
                    root_view.setVisibility(View.VISIBLE);
                }
                isCallPhone = true;
//                isAnswer = true;
                isBusy = false;
                startLoadCallLogTimer();
                //点亮屏幕
                view_front_black.setVisibility(View.GONE);
                setDelayTimeToScreen();
            }

            @Override
            public void outgoingInit(LinphoneCall linphoneCall) {
                // 呼叫初始化
                super.outgoingInit(linphoneCall);
//                    chineseToSpeech.speech("正在呼叫...");
                inComingCall = false;
                targetidText.setText("呼叫中...");
                speechText("正在呼叫...");
                mHangUp.setVisibility(View.VISIBLE);
                calling_view.setVisibility(View.VISIBLE);
                if (controlView.getVisibility() == View.VISIBLE) {
                    controlView.setVisibility(View.GONE);
                    root_view.setVisibility(View.VISIBLE);
                }

                isCallPhone = true;
//                isAnswer = false;
                isBusy = true;
                view_front_black.setVisibility(View.GONE);
                setDelayTimeToScreen();
            }

            @Override
            public void callConnected(LinphoneCall linphoneCall) {
                // 电话接通
                super.callConnected(linphoneCall);
                inComingCall = false;
                // 视频通话默认免提，语音通话默认非免提
                EasyLinphone.toggleSpeaker(EasyLinphone.getVideoEnabled());
                // 所有通话默认非静音
                EasyLinphone.toggleMicro(false);
                mCallIn.setVisibility(View.GONE);
                mHangUp.setVisibility(View.VISIBLE);
                mToggleSpeaker.setVisibility(View.VISIBLE);
                mToggleMute.setVisibility(View.VISIBLE);
                targetidText.setText("通话中...");
                speechText("已接通...");
                calling_view.setVisibility(View.VISIBLE);
                isBusy = true;
                isCallPhone = true;
            }

            @Override
            public void paused(LinphoneCall linphoneCall) {
                super.paused(linphoneCall);
                inComingCall = false;
                mCallIn.setVisibility(View.GONE);
                mHangUp.setVisibility(View.VISIBLE);
                mToggleSpeaker.setVisibility(View.VISIBLE);
                mToggleMute.setVisibility(View.VISIBLE);
                targetidText.setText("暂停通话...");
                speechText("暂停通话...");
                calling_view.setVisibility(View.VISIBLE);
                isBusy = true;
                isCallPhone = true;
            }

            @Override
            public void Resuming(LinphoneCall linphoneCall) {
                super.Resuming(linphoneCall);
                inComingCall = false;
                mCallIn.setVisibility(View.GONE);
                mHangUp.setVisibility(View.VISIBLE);
                mToggleSpeaker.setVisibility(View.VISIBLE);
                mToggleMute.setVisibility(View.VISIBLE);
                targetidText.setText("通话中...");
                speechText("恢复通话...");
                calling_view.setVisibility(View.VISIBLE);
                isBusy = true;
                isCallPhone = true;
            }

            @Override
            public void callEnd(LinphoneCall linphoneCall) {
                // 电话挂断
                super.callEnd(linphoneCall);
                inComingCall = false;
                speechText("结束通话...");
                calling_view.setVisibility(View.GONE);
                mCallIn.setVisibility(View.GONE);
                mHangUp.setVisibility(View.VISIBLE);
                mToggleMute.setVisibility(View.INVISIBLE);
                mToggleSpeaker.setVisibility(View.INVISIBLE);
                targetidText.setText("结束通话...");
                Log.e("linphone", "callEnd" + linphoneCall);
                isBusy = false;
                isCallPhone = false;
                calling_view.setVisibility(View.GONE);
            }

            @Override
            public void error() {
                super.error();
                speechText("通话异常,请重试...");
                calling_view.setVisibility(View.GONE);
                mCallIn.setVisibility(View.GONE);
                mHangUp.setVisibility(View.VISIBLE);
                mToggleMute.setVisibility(View.INVISIBLE);
                mToggleSpeaker.setVisibility(View.INVISIBLE);
                targetidText.setText("异常结束...");
                Log.e("linphone", "error");
                isBusy = false;
                isCallPhone = false;
            }

            @Override
            public void callReleased(LinphoneCall linphoneCall) {
                super.callReleased(linphoneCall);
                // 电话挂断
                super.callEnd(linphoneCall);
                if (isBusy) {
                    speechText("结束通话...");
                }
                calling_view.setVisibility(View.GONE);
                mCallIn.setVisibility(View.GONE);
                mHangUp.setVisibility(View.VISIBLE);
                mToggleMute.setVisibility(View.INVISIBLE);
                mToggleSpeaker.setVisibility(View.INVISIBLE);
                targetidText.setText("结束通话...");
                Log.e("linphone", "callEnd" + linphoneCall);
                isBusy = false;
                isCallPhone = false;
            }
        };
        EasyLinphone.addCallback(new RegistrationCallback() {
            @Override
            public void registrationOk() {
                super.registrationOk();
                LoadDialog.dismiss(getActivity());
                showToast("登录成功！");
            }

            @Override
            public void registrationFailed() {
                LoadDialog.dismiss(getActivity());
                super.registrationFailed();
                showToast("登录失败！");
            }

            @Override
            public void registrationProgress() {
                super.registrationProgress();
                LoadDialog.show(getActivity(), "登录中");
            }

            @Override
            public void registrationNone() {
                super.registrationNone();
            }

            @Override
            public void registrationCleared() {
                super.registrationCleared();
            }
        }, phoneCallback);

        if (TextUtils.isEmpty(linPhonDataIp) || TextUtils.isEmpty(linPhonDataDq) ||
                TextUtils.isEmpty(linPhonDataZh) || TextUtils.isEmpty(linPhonDataMm)) {
            startActivity(new Intent(getActivity(), ControllerActivity.class));
        } else {
            EasyLinphone.setAccount(linPhonDataZh, linPhonDataMm, linPhonDataIp + ":" + "5060");
            EasyLinphone.login();
        }
    }



    @Override
    protected CurrencyPresenter createP() {
        return new CurrencyPresenter();
    }

    @Override
    protected int setview() {
        return R.layout.fr_wardround_ly;
    }

    @Override
    protected void initview() {


        wardroundName = (TextView) findviewById(R.id.wardround_name);
        wardroundAge = (TextView) findviewById(R.id.wardround_age);
        wardroundTime = (TextView) findviewById(R.id.wardround_time);
        wardroundStarts = (TextView) findviewById(R.id.wardround_starts);
        myRecyclerView = (RecyclerView) findviewById(R.id.myRecyclerView);
        lastPage = (TextView) findviewById(R.id.last_page);
        nextPage = (TextView) findviewById(R.id.next_page);

        wardroundName.setText(UserInfo.UserName);
        wardroundAge.setText(UserInfo.UserAge);
        wardroundTime.setText(UserInfo.UserTime);
        wardroundStarts.setText(UserInfo.UserType);

        myRecycleAdapter = new MyRecycleAdapter<WardRoundEntity.DataBean>(getContext(),
                arrayList, R.layout.item_wardround_ly, false) {
            @Override
            protected void setPositionClick(int position) {

            }

            @Override
            protected void initData(MyViewHolder holder, int position) {
                if (position % 2 == 0) {
                    holder.getView(R.id.item_wardround).setBackgroundColor(Color.parseColor("#D4DFFF"));
                } else {
                    holder.getView(R.id.item_wardround).setBackgroundColor(Color.parseColor("#F7F7F7"));
                }

                WardRoundEntity.DataBean dataBean = arrayList.get(position);
                holder.setText(R.id.item_wardround_mc, dataBean.getName());
                holder.setText(R.id.item_wardround_fl, dataBean.getCate());
                holder.setText(R.id.item_wardround_zc, dataBean.getZhicheng());
                holder.setText(R.id.item_wardround_sj, dataBean.getVisit_time());
            }
        };
        UtilsManage utilsManage = new UtilsManage(getContext());
        myRecyclerView.setLayoutManager(utilsManage.linearLayoutManager(getContext(),
                LinearLayout.VERTICAL, true));
        myRecyclerView.setAdapter(myRecycleAdapter);

        requestIndexVisitlog();
        initView();
        initLinPhoneCall();
    }

    /**
     * 查房记录 /api/index/visitlog
     */
    private int index_visitlog = 1;

    private void requestIndexVisitlog() {
        HashMap<String, String> hashMap = new HashMap<>();
        // hashMap.put("house_id", shareference.getUserHouseID());
        hashMap.put("maternal_id", "4");
        getP().requestGet(index_visitlog, urlManage.APP_URL + "index/visitlog", hashMap);
    }

    @Override
    public void requestCurrencyView(int type, String body) {
        WardRoundEntity wardRoundEntity = new Gson().fromJson(body, WardRoundEntity.class);
        arrayList.clear();
        for (WardRoundEntity.DataBean bean : wardRoundEntity.getData()) {
            arrayList.add(bean);
        }
        myRecycleAdapter.notifyDataSetChanged();
    }

    @Override
    public void requestCurrencyViewFailed(int type, int code) {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        chineseToSpeech.destroy();
        LinphoneService.removeAllCallback();
    }


    // 点击接听
    public void acceptCall() {
        changeCallStatus("1");
        EasyLinphone.acceptCall();
        isUpDateStatus = false;
    }

    // 挂断
    public void hangUp() {
        if (isUpDateStatus) {
            changeCallStatus("3");
        } else {
//            changeCallStatus("5");
        }
        EasyLinphone.hangUp();
        isBusy = false;
        isCallPhone = false;
        isUpDateStatus = true;
    }
    private void changeCallStatus(String status) {
//        if (TextUtils.isEmpty(callingLogId)) {
//            Log.d("callingLogId", "callingLogId:" + callingLogId);
//            return;
//        }
//        HashMap<String, String> hashMap = new HashMap<>();
//        hashMap.put("id", callingLogId);
//        hashMap.put("call_status", status);
//        getP().requestGet(index_change_call_status, UrlManage.APP_URL + "/doctor/editcall", hashMap);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.btn_closeScreen:
                //息屏
                view_front_black.setVisibility(View.VISIBLE);
                view_front_black.setTag(0);

            case R.id.accept_call:
                // 接听
                mCallIn.setVisibility(View.GONE);
                acceptCall();
                break;
            case R.id.hang_up:
                // 挂断
                calling_view.setVisibility(View.GONE);
                hangUp();
                break;

        }
    }
}
